package com.zh.web.config;

import com.zh.common.properties.JwtProperties;
import feign.Logger;
import feign.RequestInterceptor;
import feign.form.spring.SpringFormEncoder;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Configuration
@RequiredArgsConstructor
public class DefaultFeignConfig {

    private final JwtProperties jwtProperties;

    @Bean
    public Logger.Level feignLogLevel() {
        return Logger.Level.BASIC;
    }


    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            // 获取当前请求的 HttpServletRequest
            if (servletRequestAttributes != null) {
                HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
                // 从请求头中获取 Authentication
                String authenticationHeader = request.getHeader(jwtProperties.getTokenName());
                // 将 Authentication 添加到 Feign 请求中
                if (authenticationHeader != null) {
                    requestTemplate.header(jwtProperties.getTokenName(), authenticationHeader);
                }
            }
        };
    }
}